package com.example.baguwen.config;

import com.example.baguwen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    
    // 不需要登录就可以访问的路径
    private static final List<String> PUBLIC_PATHS = Arrays.asList(
            "/api/user/login",
            "/api/user/register",
            "/api/user/check-username",
            "/",
            "/index.html",
            "/login.html",
            "/favicon.ico",
            "/**/*.js",
            "/**/*.css",
            "/**/*.png",
            "/**/*.jpg",
            "/**/*.jpeg",
            "/**/*.gif",
            "/**/*.svg",
            "/**/*.ico",
            "/**/*.woff",
            "/**/*.woff2",
            "/**/*.ttf",
            "/**/*.eot"
    );
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求路径
        String path = request.getRequestURI();
        String method = request.getMethod();
        System.out.println("拦截请求: " + method + " " + path);
        
        // 检查是否是登录相关路径
        if (path.equals("/api/user/login") || path.equals("/api/user/register") || path.startsWith("/login")) {
            System.out.println("登录相关路径，直接放行: " + path);
            return true;
        }
        
        // 检查是否是静态资源
        if (path.contains(".")) {
            String extension = path.substring(path.lastIndexOf("."));
            if (extension.equals(".js") || extension.equals(".css") || extension.equals(".html") ||
                extension.equals(".png") || extension.equals(".jpg") || extension.equals(".ico")) {
                System.out.println("静态资源，直接放行: " + path);
                return true;
            }
        }
        
        // 检查是否是其他公开路径
        for (String publicPath : PUBLIC_PATHS) {
            if (pathMatcher.match(publicPath, path)) {
                System.out.println("公开路径，直接放行: " + path);
                return true;
            }
        }
        
        // 获取token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        // 如果未登录返回401
        if (token == null || token.isEmpty()) {
            // 如果是前端页面请求，重定向到登录页
            if (isHtmlRequest(request)) {
                System.out.println("未登录，重定向到登录页: " + path);
                response.sendRedirect("/login.html");
                return false;
            }
            
            // API请求返回401
            System.out.println("API未授权: " + path);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录\",\"data\":null}");
            return false;
        }
        
        try {
            // 验证token
            userService.getCurrentUser(token);
            return true;
        } catch (Exception e) {
            // 如果是前端页面请求，重定向到登录页
            if (isHtmlRequest(request)) {
                response.sendRedirect("/login.html");
                return false;
            }
            
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"" + e.getMessage() + "\",\"data\":null}");
            return false;
        }
    }
    
    private boolean isHtmlRequest(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        return accept != null && accept.contains("text/html");
    }
} 